<?php

namespace app\socket;

use app\socket\types\FcPlayer;
use app\socket\types\FcRoom;
use app\socket\types\Player;
use app\socket\types\SwPlayer;
use app\socket\types\SwRoom;

class User extends Base
{
    /**
     * 用户登录 
     *
     * @return void
     */
    public function onLogin()
    {
        $fd = $this->websocket->getSender();
        $player = Player::create($fd);
        $player->save();

        $this->websocket->emit("Login", [
            'player' => $player
        ]);
    }



    /**
     * 离开房间通知
     *
     * @return void
     */
    public function onClose()
    {
        $fd = $this->websocket->getSender();
        $original = Player::find($fd);

        if ($original->fd) {
            $original->delete();
            $roomId = 0;
            $res['current'] = $fd;
            if ($original->type == 1) {
                $player = FcPlayer::find($fd);
                $roomId = $player->roomId;
                $room = FcRoom::find($player->roomId);
                $room->remove($player);
                $player->delete();
            }
            if ($original->type == 2) {
                $player = SwPlayer::find($fd);
                $roomId = $player->roomId;
                $room = SwRoom::find($player->roomId);
                if ($fd == $room->fd) {
                    $next = $room->next($fd);
                    $res['next'] = $next;
                }
                $room->remove($player);
                $player->delete();
            }

            if ($roomId) { //如果玩家在房间内 通知房间内的其他人,玩家离线
                $this->websocket->to($roomId)->emit("Offline", $res);
            }
        }
    }
}
